#include "print.h"
#include "../commons/monitor.h"
#include "../commons/waiter.h"

monitor_t monitor;
mapa_t mapa;
int the_end=0;
int first_print=1;

void init_monitor(int hijos){
	pthread_mutex_init(&monitor.mutex, NULL);
	pthread_cond_init(&monitor.cond1, NULL);
	pthread_cond_init(&monitor.cond2, NULL);
	monitor.counter=0;
	monitor.limit=hijos;
 
}

void close_drawer(){
	the_end=1;
	pthread_cond_signal(&monitor.cond1);
	fflush(stdin);
}

void* drawer(void* m){
	mapa = m;

	sem_t* starter=sem_open(STARTER,0);
	int i;
	for(i=0;i<monitor.limit-1;i++){
		sem_wait(starter);
	}
	
	sem_close(starter);
	printMapa(mapa);

	first_print=0;
	pthread_cond_signal(&monitor.cond2);
	
	getchar();
	while(!the_end){

		pthread_mutex_lock(&monitor.mutex);

		int i;
		while(monitor.counter < monitor.limit){
			pthread_cond_wait(&monitor.cond1, &monitor.mutex);
			if(the_end){
				freeMapa(mapa);
				pthread_mutex_unlock(&monitor.mutex);
				pthread_mutex_destroy(&monitor.mutex);
				pthread_cond_destroy(&monitor.cond1);
				pthread_cond_destroy(&monitor.cond2);
				exit(0);
			}
		}

		printMapa(mapa);
		print_aeroplanes();
		
		monitor.counter=0;
		pthread_cond_signal(&monitor.cond2);
		pthread_mutex_unlock(&monitor.mutex);

		getchar();
		
		
	}
	
	
	free_to_print();
	freeMapa(mapa);
	pthread_mutex_destroy(&monitor.mutex);
	pthread_cond_destroy(&monitor.cond1);
	pthread_cond_destroy(&monitor.cond2);
	
}
